<template>
  <div class="article-edit">
    <h2>编辑文章</h2>
    <form v-if="article" @submit.prevent="handleSubmit" class="edit-form">
      <div class="form-item">
        <label>标题：</label>
        <input type="text" v-model="article.title" required />
      </div>
      <div class="form-item">
        <label>简介：</label>
        <textarea v-model="article.summary" rows="3" required placeholder="请输入文章简介，最多200字" maxlength="200"></textarea>
      </div>
      <div class="form-item">
        <label>分类：</label>
        <select v-model="article.category" required>
          <option value="时尚">时尚</option>
          <option value="美食">美食</option>
          <option value="旅游">旅游</option>
          <option value="音乐">音乐</option>
          <option value="生活">生活</option>
          <option value="健身">健身</option>
          <option value="体育">体育</option>
          <option value="DIY">DIY</option>
          <option value="财务">财务</option>
          <option value="政治">政治</option>
          <option value="其他">其他</option>
        </select>
      </div>
      <div class="form-item">
        <label>内容：</label>
        <textarea v-model="article.content" rows="10" required></textarea>
      </div>
      <div class="form-actions">
        <button type="submit" class="btn-save">保存</button>
        <button type="button" @click="handleCancel" class="btn-cancel">取消</button>
      </div>
    </form>
    <div v-else>加载中...</div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getBlogById, updateBlog } from '../api/blog'

const route = useRoute()
const router = useRouter()
const article = ref(null)

const fetchArticle = async () => {
  try {
    article.value = await getBlogById(route.params.id)
  } catch (error) {
    console.error('获取文章失败：', error)
    alert('获取文章失败')
    router.push('/')
  }
}

const handleSubmit = async () => {
  try {
    await updateBlog(route.params.id, article.value)
    alert('保存成功')
    router.push(`/article/${route.params.id}`)
  } catch (error) {
    alert('保存失败：' + error.message)
  }
}

const handleCancel = () => {
  router.back()
}

onMounted(() => {
  fetchArticle()
})
</script>

<style scoped>
.article-edit {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.edit-form {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

input, textarea {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.form-actions {
  display: flex;
  gap: 10px;
}

.btn-save, .btn-cancel {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-save {
  background-color: #4CAF50;
  color: white;
  border: none;
}

.btn-cancel {
  background-color: #f5f5f5;
  color: #333;
  border: 1px solid #ddd;
}
</style> 